class Solution {
    public String decodeString(String s) {
        LinkedList<Character> stack = new LinkedList<>();

        for (char c : s.toCharArray()){
            if (c != ']')
                stack.push(c);
            else {
                // 1. 取出[]内的字符串
                StringBuilder sb = new StringBuilder();
                while(!stack.isEmpty() && Character.isLetter(stack.peek()))
                    sb.insert(0, stack.pop());
                
                String sub = sb.toString();
                stack.pop(); // 弹出[

                // 2. 获取倍数数字
                sb = new StringBuilder();
                while(!stack.isEmpty() && Character.isDigit(stack.peek()))
                    sb.insert(0, stack.pop());

                int count = Integer.valueOf(sb.toString());

                // 3. 根据倍数把字母push回去
                while(count > 0){
                    for (char ch : sub.toCharArray())
                        stack.push(ch);
                    count--;
                }
            }
        }

        StringBuilder retv = new StringBuilder();
        while(!stack.isEmpty()){
            retv.insert(0, stack.pop());
        }

        return retv.toString();
    }
}